<?php
/*
 * Created on Mar 1, 2010
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
?>
<?php
require_once APPPATH . "controllers/cmsbase.php";
class cms_gallery extends CmsBase {

	var $_require_login = true;
	var $upload_config = null;
	var $image_toolkit = null;
	var $mimes = null;

	function __construct() {
		parent :: __construct();
		// Check permission
		parent::_check_permission('pms_gallery');
		$this->load->library('pagination');
		$this->load->model('Model_mediaset', 'model_mediaset');
		$this->load->model('Model_media', 'model_media');

		$image_toolkit = $this->_settings['image_toolkit'];
		$this->image_toolkit = unserialize($image_toolkit);
	}

	/**
	 * Name: index
	 * Param: pagination param
	 * Description:
	 *
	 */
	function index(){
		// Load pagination
		$this->javascript .= $this->_load_javascript("public/js/eye");
		$this->javascript .= $this->_load_javascript("public/js/utils");
		$this->javascript .= $this->_load_javascript("public/js/zoomimage");
		$this->css .= link_tag("public/css/zoomimage.css");
		return $this->_render_my_view(array());
	}
	/**
	 * Name: browse_set
	 * Param: pagination param
	 * Description:
	 *
	 */
	function browse_set(){
		// Load pagination
		$keyword = "";
		$fromdate = "";
		$todate = "";
		$set_list = $this->model_mediaset->browse($keyword, $fromdate, $todate);
		return $this->load->view("cms_gallery/browse_set", array("set_list" => $set_list));
	}
	/**
	 * Name: browse_media
	 * Param: pagination param
	 * Description:
	 *
	 */
	function browse_media(){
		// Load pagination
		$keyword = "";
		$group = $this->input->post("group")*1;
		$fromdate = $this->input->post("fromdate");
		$todate = $this->input->post("todate");
		$limit = 50;

		$offset = $this->uri->segment(3,0);

		$media_set = $this->model_mediaset->find($group);
		$media_set_arr = null;
		if($media_set)
			$media_set_arr = $media_set['media_ids'];

		$img_list = $this->model_media->browse($keyword, $fromdate, $todate, $limit,$offset,$media_set_arr);
		$count_list = $this->model_media->browse_count($keyword, $fromdate, $todate,$media_set_arr);

		$set_list = $this->model_mediaset->fetch_all();

		$media_thumb = $this->config->item("media_thumb");

		$config['base_url'] = base_url()."admin.php/".$this->controller_name."/browse_media/";
		$config['total_rows'] = $count_list;
		$config['per_page'] = $limit;

		$this->pagination->initialize($config);
		return $this->load->view("cms_gallery/browse_media",
								  array("img_list" => $img_list,
										"image_toolkit" => $this->image_toolkit,
										"media_thumb" => $media_thumb,
										"media_set" => $set_list,
										"group" => $group,
										"fromdate" => $fromdate,
										"todate" => $todate
								));
	}

	/**
	 *
	 *
	 */
	function add_media(){
		if (isset($_POST["PHPSESSID"])) {
			ini_set("html_errors", "0");
			// Load option from setting

			$config = $this->config->item("media_default");
			$config['max_size']	= $this->image_toolkit['max_size'];
			$config['max_width']  = $this->image_toolkit['large_width'];
			$config['max_height']  = $this->image_toolkit['large_height'];
			// Load library upload
			$this->load->library('upload', $config);
			if ( ! $this->upload->do_upload("Filedata"))
			{
				//$error = array('error' => $this->upload->display_errors());
				echo "ERROR:".$this->upload->display_errors();
			}
			else
			{
				// Get the image and create a thumbnail
				$data = $this->upload->data();
				$media = array('title' => $data['raw_name'],
								'filename' => $data['file_name'],
								'rawname' => $data['raw_name'],
								'filetype' => $data['file_type'],
								'filesize' => $data['file_size'],
								'fileext' => $data['file_ext'],
								'isimage' => $data['is_image']);

				$config = $this->config->item('media_thumb');
				$config['source_image'] = $data['full_path'];
				$config['width'] = $this->image_toolkit['thumb_width'];
				$config['height'] = $this->image_toolkit['thumb_height'];
				$this->load->library('image_lib', $config);
				if ( ! $this->image_lib->resize())
				{
				    echo  "ERROR:".$this->image_lib->display_errors();
					exit(0);
				}
				$this->image_lib->clear();

				// Save to database
				$id = $this->model_media->insert_media($media);
				echo "FILEID:".$id;
				exit(0);
			}
		}
		else{
			$this->javascript .= $this->_load_javascript("public/admin/js/swfupload/swfupload");
			$this->javascript .= $this->_load_javascript("public/js/handlers");
			$this->javascript .= $this->_load_javascript("public/js/fileprogress");
			$this->javascript .= $this->_load_javascript("public/js/swfupload.queue");
			$this->css .= link_tag("public/admin/css/swfupload.css");
			return $this->_render_my_view(array());
		}
	}
	
	function edit_media($id = 0)
	{
		if(intval($id)){
			if($_SERVER['REQUEST_METHOD'] === 'POST')
			{
				// update Newsletter
				$data = parse_input('media_', $_POST);
				// Check Upload file
				$result = array('status' => 'success',
								'message' => 'You have just update a record',
								'id' => $id,
								'media_title'=> $data['title']);				
				$this->model_media->update_media($id, $data);
				
				echo json_encode($result);
				exit;
			}
			else{				
				$document = $this->model_media->find($id);
				$media_thumb = $this->config->item("media_thumb");
				return $this->load->view("cms_gallery/edit_media", array("media" => $document, 'media_thumb' => $media_thumb));
			}
		}
	}
	/**
	 *
	 *
	 */
	function add_set(){
		if($_SERVER['REQUEST_METHOD'] === 'POST')
		{
			$data = parse_input('item_', $_POST);
			if(isset($data['media_ids'])){
				$data['media_ids'] = implode(",", $data['media_ids']);
			}
			$id = $this->model_mediaset->insert_mediaset($data);
			redirect(site_url(array("c" => 'cms_gallery', 'm' => "index")), 'refresh');
		}
		else{
			$keyword = "";
			$fromdate = "";
			$todate = "";
			$limit = 10;

			$offset = $this->uri->segment(4,0);


			$img_list = $this->model_media->browse($keyword, $fromdate, $todate,$limit,$offset);
			$media_thumb = $this->config->item("media_thumb");

			$count_list = $this->model_media->browse_count($keyword, $fromdate, $todate);

			$config['base_url'] = base_url()."admin.php/".$this->controller_name."/show_media/";
			$config['total_rows'] = $count_list;
			$config['per_page'] = $limit;


			$this->pagination->initialize($config);

			return $this->_render_my_view(array("image_toolkit" => $this->image_toolkit, "img_list" => $img_list, "media_thumb" => $media_thumb));
		}
	}
	/**
	 *
	 *
	 */
	function edit_set($id){
		if($_SERVER['REQUEST_METHOD'] === 'POST')
		{
			$data = parse_input('item_', $_POST);
			if(isset($data['media_ids'])){
				$data['media_ids'] = implode(",", $data['media_ids']);
			}
			$this->model_mediaset->update_mediaset($id, $data);
			redirect(site_url(array("c" => 'cms_gallery', 'm' => "index")), 'refresh');
		}
		else{
			$keyword = "";
			$fromdate = "";
			$todate = "";
			$set = $this->model_mediaset->find($id);
			$mediaIds = explode(",", $set['media_ids']);
			$mediaChosen = $this->model_media->find_by_ids($mediaIds);
			$limit = 10;

			$offset = $this->uri->segment(4,0);


			$img_list = $this->model_media->browse($keyword, $fromdate, $todate, $limit,$offset);
			$count_list = $this->model_media->browse_count($keyword, $fromdate, $todate);

			$media_thumb = $this->config->item("media_thumb");


			$config['base_url'] = base_url()."admin.php/".$this->controller_name."/show_media/";
			$config['total_rows'] = $count_list;
			$config['per_page'] = $limit;


			$this->pagination->initialize($config);


			return $this->_render_my_view(array("image_toolkit" => $this->image_toolkit, "set" => $set,"img_list" => $img_list, "media_thumb" => $media_thumb, "media_chosen" => $mediaChosen));
		}
	}
	/**
	 *
	 *
	 */
	function thumbnail($image_id){
		if ($image_id === false) {
			header("HTTP/1.1 500 Internal Server Error");
			echo "No ID";
			exit(0);
		}
		$media = $this->model_media->find($image_id);
		if (empty($media)) {
			header("HTTP/1.1 404 Not found");
			exit(0);
		}
		$config = $this->config->item("media_thumb");
		$filepath = $config['upload_path'] . $media['rawname'] . $config['thumb_marker'] . $media['fileext'];
		$filetype = $media['filetype'];
		$fileext = strtolower(substr($media['fileext'], 1));
		$mime_type = $this->mimes_types($fileext);

		if(!empty($mime_type)){
			$filetype = is_array($mime_type) ? $mime_type[0] : $mime_type;
		}
		$size = getimagesize($filepath);
		//var_dump($size);exit;
		switch ($size[2])
	    {
	        case 1: $im = imagecreatefromgif($filepath); break;
	        case 2: $im = imagecreatefromjpeg($filepath); break;
	        case 3:				 
				$im = imagecreatefrompng($filepath);
				imagealphablending($im, false);
			    $colorTransparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
			    imagefill($im, 0, 0, $colorTransparent);
			    imagesavealpha($im, true); 
				break;
	        default: return '';  break;
	    }		
		/*header("Accept-Ranges: bytes");
		header("Expires:" . date('D, d M Y h:m:s'));*/
		header("Content-Length: " . filesize($filepath));
		header("Content-Type:" . $filetype);
	
		switch ($size[2])
	    {
	        case 1: imagegif($im); break;
	        case 2: imagejpeg($im);  break;
	        case 3: imagepng($im); break;
	        default: return '';  break;
	    }		
		imagedestroy($im);
		exit(0);
	}

	/**
	 *
	 *
	 */
	function delete_set($set_id){
		// Delete source image on hdd
		$this->model_mediaset->delete_mediaset($set_id);
		//log_message("error", $this->db->last_query());
		$result = array('status' => 'success', 'message' => 'Deleted', 'mediaset_id' => $set_id);
		echo json_encode($result);
		exit;
	}

	/**
	 *
	 *
	 */
	function delete_media($image_id){
		// Delete source image on hdd
		if ($image_id === false) {
			header("HTTP/1.1 500 Internal Server Error");
			echo "No ID";
			exit(0);
		}
		$media = $this->model_media->find($image_id);
		if (empty($media)) {
			header("HTTP/1.1 404 Not found");
			exit(0);
		}
		$config = $this->config->item("media_thumb");
		$filepath = $config['upload_path'] . $media['rawname'] . $config['thumb_marker'] . $media['fileext'];
		if(is_file($filepath)){
			unlink($filepath);
		}
		$this->model_media->delete_media($image_id);
		//log_message("error", $this->db->last_query());
		$result = array('status' => 'success', 'message' => 'Deleted', 'image_id' => $image_id);
		echo json_encode($result);
		exit;
	}

	/**
	 * List of Mime Types
	 *
	 * This is a list of mime types.  We use it to validate
	 * the "allowed types" set by the developer
	 *
	 * @access	public
	 * @param	string
	 * @return	string
	 */
	function mimes_types($mime)
	{
		global $mimes;

		if (count($this->mimes) == 0)
		{
			if (@require_once(APPPATH.'config/mimes'.EXT))
			{
				$this->mimes = $mimes;
				unset($mimes);
			}
		}

		return ( ! isset($this->mimes[$mime])) ? FALSE : $this->mimes[$mime];
	}

	function show_media(){
		$keyword = "";
		$fromdate = "";
		$todate = "";
		$limit = 10;

		$offset = $this->uri->segment(3,0);

		$img_list = $this->model_media->browse($keyword, $fromdate, $todate, $limit,$offset);
		$count_list = $this->model_media->browse_count($keyword, $fromdate, $todate);

		$media_thumb = $this->config->item("media_thumb");


		$config['base_url'] = base_url()."admin.php/".$this->controller_name."/show_media/";
		$config['total_rows'] = $count_list;
		$config['per_page'] = $limit;


		$this->pagination->initialize($config);
		return $this->load->view("cms_gallery/show_media",array("img_list" => $img_list, "media_thumb" => $media_thumb));
	}

}
